package com.walnut.dao;

import com.walnut.model.Immortal;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;

import java.util.List;

/**
 * Created by parker on 15/4/5.
 */
public class ImmortalDaoImpl implements ImmortalDAO {
    /**
     * Session factory injected by spring context
     */
    private SessionFactory sessionFactory;
    /**
     * insert a new immortal entity into the datasource
     *
     * @param immortal the candidate
     */
    @Override
    public void addImmortal(Immortal immortal) {
        sessionFactory.getCurrentSession().save(immortal);
    }

    /**
     * delete the specific immortal entity
     *
     * @param immortalId the unique identity of the specific immortal
     */
    @Override
    public void deleteImmortal(Integer immortalId) {
        String sql = "delete immortal where id = :id";
        Query query = sessionFactory.getCurrentSession().createQuery(sql).setParameter("id", immortalId);
        query.executeUpdate();
    }

    /**
     * retrieve the all immortals entities
     *
     * @return
     */
    @Override
    public List<Immortal> getAllImmortals() {
        return sessionFactory.getCurrentSession().createQuery("from immortal").list();
    }

    /**
     * retrieve the detail info of the specific immortal
     *
     * @param immortalId
     * @return
     */
    @Override
    public Immortal getImmortal(Integer immortalId) {
        return (Immortal) sessionFactory.getCurrentSession().get(Immortal.class, immortalId);
    }

    /**
     * retrieve the detail info of the specific immortal
     *
     * @param immortalId
     * @param selected
     * @return
     */
    @Override
    public Immortal getImmortal(Integer immortalId, String selected) {
        String sql = "select " + selected + " from immortal where id = :id";
        Query query = sessionFactory.getCurrentSession().createSQLQuery(sql)
                .setParameter("id", immortalId)
                .setResultTransformer(Transformers.aliasToBean(Immortal.class));
        return (Immortal) query.list().get(0);
    }

    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }
}
